﻿package com.cn.hnust.controller;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.imageio.ImageIO;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.cn.hnust.pojo.User;
import com.cn.hnust.service.IUserService;

import com.cn.hnust.util.Page;


@Controller
@RequestMapping("/user")
public class UserController {

	@Autowired
	private IUserService userService;

	@RequestMapping(value = "/showUser")
	public String toIndex(Model model) throws Exception {
		List<User> users = userService.getUsers();
		 
		model.addAttribute("users", users);
		return "adv";
	}

	@RequestMapping(value = "/login")
	public String login(HttpSession session) {
		session.removeAttribute("userid");
		
		return "login";
	}

	@RequestMapping(value = "/index")
	public String index(){
		
		return "redirect:/index.jsp";
	}
	
	@RequestMapping(value = "/LoginSuccess")
	@ResponseBody
	public Map<String, Object> loginyz(String userName,String password,HttpServletRequest request,HttpSession session) {
		 //String verifyCode = String.valueOf(request.getSession().getAttribute("strCode"));
		 Object strCode = session.getAttribute("strCode");
		 Map<String, Object> Map = new HashMap<String, Object>();
		 
		 System.out.println(strCode);
		User u = userService.getUser(userName);
		session.setAttribute("userid", u.getUserName());
		if (userName.equals(u.getUserName()) && password.equals(u.getPassword())) {
			Map.put("yzm", strCode);
			Map.put("userName", userName);
			Map.put("password",password);
			
		} else {
			Map.put("shibai", "失败");
		}
		return Map;
	}
	
/**
 * 用户删除
 */
	@RequestMapping(value = "/delUser")
	@ResponseBody
	public Map<String,Object> delUser(int id,Model model) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		userService.delUser(id);
		int pageNow1 = 1;
		
		Page page = null;// new 对象在下面
		int totalCount = userService.getCount();// 获取当前用户总记录条数
//	}else if (pageNow != null && pageNow != "") {// 防止出现空指针异常
//			int pageNow1 = Integer.parseInt(pageNow);
			page = new Page(totalCount, pageNow1);// 这样写的好处，判断完成外面可以继续调用
		List<User> users = userService.queryAllRecord(page);
		model.addAttribute("page", page);
//		List<User> users = userService.getUsers();
		model.addAttribute("users", users);
		resultMap.put("result", "删除");
		return resultMap;

	}

	@RequestMapping(value = "useradd")
	public String Useradd() {
		return "useradd";
	}

	@RequestMapping(value = "userinsert")
	@ResponseBody
	public Map<String,Object> userinsert(Model model,String userName,String password) {
//		String userName=request.getParameter("userName");
//		String password=request.getParameter("password");
		int pageNow1 = 1;
		User user=new User();
		user.setUserName(userName);
		user.setPassword(password);
		Map<String, Object> resultMap = new HashMap<String, Object>();
		if(userName.matches("^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$")){
			int a=userService.insert(user);
			if (a > 0) {
				Page page = null;// new 对象在下面
				int totalCount = userService.getCount();// 获取当前用户总记录条数
				
//			}else if (pageNow != null && pageNow != "") {// 防止出现空指针异常
//					int pageNow1 = Integer.parseInt(pageNow);
				page = new Page(totalCount, pageNow1);// 这样写的好处，判断完成外面可以继续调用
				
				model.addAttribute("page", page);
				
				List<User> users = userService.getUsers();
				model.addAttribute("users", users);
				resultMap.put("success", "1");
				return resultMap;
//				return "adv";
			
		}
		} else {
			resultMap.put("error", "2");
			return resultMap;
//			return "useradd";
		}
		return resultMap;

	}

	@RequestMapping(value = "/Userupdate")
	public String Userxg(HttpServletRequest request, Model model,String userName) {
		
		User users=userService.getUser(userName);
		model.addAttribute("users", users);
		
		
		return "Useruqdate";
		
		
	}
	
	@RequestMapping(value = "/Usersuccess")
	public String Usercg(String username,HttpServletRequest request, Model model,int user_id) {
		String userName=request.getParameter("userName");
		String password=request.getParameter("password");
		int pageNow1 = 1;
		
		User user = new User();
		user.setUser_id(user_id);
		
		user.setUserName(userName);
		user.setPassword(password);
		userService.updateByPrimaryKey(user);
		Page page = null;// new 对象在下面
			int totalCount = userService.getCount();// 获取当前用户总记录条数
	
//		}else if (pageNow != null && pageNow != "") {// 防止出现空指针异常
//				int pageNow1 = Integer.parseInt(pageNow);
				page = new Page(totalCount, pageNow1);// 这样写的好处，判断完成外面可以继续调用
			
			model.addAttribute("page", page);
		
		List<User> users=userService.selectPersons(userName, page);
		model.addAttribute("users", users);
		
		
		return "adv";
		
		
	}


	@RequestMapping(value = "/usermh")
	public String usermh(HttpServletRequest request, Model model) {
String userName=request.getParameter("userName");
		
		String userNam="%"+userName+"%";
		
		int pageNow1 = 1;
		
		Page page = null;// new 对象在下面
		int totalCount = userService.getCount();// 获取当前用户总记录条数

//	}else if (pageNow != null && pageNow != "") {// 防止出现空指针异常
//			int pageNow1 = Integer.parseInt(pageNow);
			page = new Page(totalCount, pageNow1);// 这样写的好处，判断完成外面可以继续调用
		List<User> users = userService.selectPersons(userNam, page);
		model.addAttribute("page", page);
		
		model.addAttribute("users", users);
		
		return "adv";

	}
	
	@RequestMapping(value="/queryAll")
	 public String record(Model model, String pageNow){
       
        Page page = null;//new 对象在下面
        
       int totalCount = userService.getCount();//获取当前用户总记录条数
        
        if(pageNow != null && pageNow != "") {//防止出现空指针异常
            int pageNow1 = Integer.parseInt(pageNow);
            page = new Page(totalCount, pageNow1);//这样写的好处，判断完成外面可以继续调用
        }  
        List<User> users = userService.queryAllRecord(page);//取得当前用户的所有操作记录
        model.addAttribute("page",page);
        model.addAttribute("users",users);
        
        return "adv";
    }
	
	
	@RequestMapping({"authCode"})
    public void getAuthCode(HttpServletRequest request, HttpServletResponse response,HttpSession session)
            throws IOException {
        int width = 63;
        int height = 37;
        Random random = new Random();
        //设置response头信息
        //禁止缓存
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        //生成缓冲区image类
        BufferedImage image = new BufferedImage(width, height, 1);
        //产生image类的Graphics用于绘制操作
        Graphics g = image.getGraphics();
        //Graphics类的样式
        g.setColor(this.getRandColor(200, 250));
        g.setFont(new Font("Times New Roman",0,28));
        g.fillRect(0, 0, width, height);
        //绘制干扰线
        for(int i=0;i<40;i++){
            g.setColor(this.getRandColor(130, 200));
            int x = random.nextInt(width);
            int y = random.nextInt(height);
            int x1 = random.nextInt(12);
            int y1 = random.nextInt(12);
            g.drawLine(x, y, x + x1, y + y1);
        }

        //绘制字符
        String strCode = "";
        for(int i=0;i<4;i++){
            String rand = String.valueOf(random.nextInt(10));
            strCode = strCode + rand;
            g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110)));
            g.drawString(rand, 13*i+6, 28);
        }
        //将字符保存到session中用于前端的验证
        session.setAttribute("strCode", strCode);
        g.dispose();

        ImageIO.write(image, "JPEG", response.getOutputStream());
        response.getOutputStream().flush();

    }
	//创建颜色
    Color getRandColor(int fc,int bc){
        Random random = new Random();
        if(fc>255)
            fc = 255;
        if(bc>255)
            bc = 255;
        int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);
        return new Color(r,g,b);
    }
    
    @RequestMapping(value = "/qdlogin")
	public String Qdlogin() {
		
		
		return "reception/index";
	} 

}
